package tech.abing.spider.monitor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tech.abing.spider.CrawlTask;
import tech.abing.spider.task.utils.TaskUtil;

/**
 * 监控爬虫状态MXBean的实现类
 * 
 * @author Ivan qb.huang@wescxx.com
 * @date 2016-11-11 上午10:19:12
 * @version V2.0
 */
public class SpiderStatus implements SpiderStatusMXBean {

	protected final CrawlTask spider;

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected final SpiderMonitor.MonitorSpiderListener monitorSpiderListener;

	public SpiderStatus(CrawlTask spider, SpiderMonitor.MonitorSpiderListener monitorSpiderListener) {
		this.spider = spider;
		this.monitorSpiderListener = monitorSpiderListener;
	}

	public String getName() {
		return spider.getTaskName();
	}

	@Override
	public int getSuccessPageCount() {
		return monitorSpiderListener.getSuccessCount().get();
	}

	@Override
	public int getErrorPageCount() {
		return monitorSpiderListener.getErrorCount().get();
	}

	public List<String> getErrorPages() {
		return monitorSpiderListener.getErrorUrls();
	}

	@Override
	public String getStatus() {
		return spider.isRuning() ? "抓取中" : "停止";
	}

	@Override
	public int getThread() {
		return spider.getDownloadThreadPool().getThreadNum();
	}

	public void start() {
		spider.start();
	}

	public void stop() {
		spider.stop();
	}

	@Override
	public Date getStartTime() {
		return spider.getStartTime();
	}

	@Override
	public int getPagePerSecond() {
		int runSeconds = (int) (System.currentTimeMillis() - getStartTime().getTime()) / 1000;
		return getSuccessPageCount() / runSeconds;
	}

	@Override
	public String getUsedTime() {
		long runSeconds = System.currentTimeMillis() - getStartTime().getTime();

		return TaskUtil.formatTime(runSeconds);
	}

}
